<?php

namespace common\components;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use api\exceptions\OperateException;
use common\helpers\StatusCode;


class Sms
{
    const ACCESS_KEY_ID = '';
    const ACCESS_SECRET = '';
    const SIGN_NAME = '';
    const TEMPLATE_CODE = '';

    /**
     * @param $mobile
     * @param $params
     * @return bool
     * @throws OperateException
     */
    public function sendSms($mobile, $params)
    {
        AlibabaCloud::accessKeyClient(self::ACCESS_KEY_ID, self::ACCESS_SECRET)
            ->regionId('cn-hangzhou')// replace regionId as you need
            ->asGlobalClient();
        try {
            $result = AlibabaCloud::rpcRequest()
                ->product('Dysmsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->options([
                    'query' => [
                        'PhoneNumbers' => $mobile,
                        'SignName' => self::SIGN_NAME,
                        'TemplateCode' => self::TEMPLATE_CODE,
                        'TemplateParam' => json_encode($params),
                    ],
                ])
                ->request();
//            print_r($result->toArray());
            $res = $result->toArray();
            if ($res['Code'] != 'OK')
                throw new OperateException(StatusCode::MEMBER_SEND_SMS_ERROR);
        } catch (ClientException $e) {
//            echo $e->getErrorMessage() . PHP_EOL;
            throw new OperateException(StatusCode::MEMBER_SEND_SMS_ERROR);
        } catch (ServerException $e) {
//            echo $e->getErrorMessage() . PHP_EOL;
            throw new OperateException(StatusCode::MEMBER_SEND_SMS_ERROR);
        }
        return true;
    }
}